const { build, context } = require('esbuild')
const path = require('path')

//解析用户执行命令行的参数
const args = require('minimist')(process.argv.slice(2))

//打包的模式是哪一个
const target = args._[0] || 'reactivity'
const format = args.f || 'global'

const pkg = require(path.resolve(__dirname, `../packages/${target}/package.json`))

const outPutFormat = format.startsWith('global') ? 'iife' : format === 'cjs' ? 'cjs' : 'esm'

const outFile = path.resolve(__dirname, `../packages/${target}/dist/${target}.${format}.js`)

async function startBuild() {
  const ctx = await context({
    entryPoints: [path.resolve(__dirname, `../packages/${target}/src/index.ts`)],
    outfile: outFile,
    bundle: true,
    sourcemap: true,
    format: outPutFormat,
    globalName: pkg.buildOptions?.name,
    platform: format === 'cjs' ? 'node' : 'browser'
  })

  await ctx.watch() // 开启 watch 模式
  console.log(`watching for changes...`)
}
startBuild().catch((err) => {
  console.error(err)
  process.exit(1)
})
